iT邦幫忙

2024 iThome 鐵人賽

DAY 12
0

上一篇我們講完了Agent以及他的相關對象的關係,
今天我們就來介紹一些不同的AgentType!


  • Zero-Shot React Description:ZeroShot(零樣本)顧名思義就是Agent在沒有任何提示或是其他外部資料、知識的情況下,直接根據user的input去運作決策,決定要用什麼tool,採取什麼操作。
  • ReAct Docstore:這個AgentType就是focus在能和文檔資料進行交互,像是檢索、對文本進行摘要、段落比較、內容引用等等,擅長使用文檔來找出解答。
  • Self-Ask with Search:除了Agent(模型)本身的推理決策,它的特色是能夠和搜索工具結合,獲取更多外部資料,因此這個AgentType就很適合應用在模型推理決策時所需的資料範圍超出本身時,像是需要即時、最新的資訊,就能透過調用網路查詢工具來取得資料。
  • Conversational React Description 和 Chat Zero-Shot React Description:這兩種類型都是針對聊天應用去設計的,兩者皆能夠處理多輪對話,可以在與使用者的持續互動中保持上下文,Conversational React Description更擅長處理多輪對話,並能夠保持對話上下文,而Chat Zero-Shot React Description更偏向於即時反應,不一定會維持長期的上下文。

那我們就馬上來實做看看吧,首先我們來看看Zero-Shot React Description

Zero-Shot React Description

這邊我們已一個做一個簡單的計算系統當作例子
首先我們先將數學運算的function以及Tool創建出來,創了計算平方根以及平方的func,並將相對應的tool對象建立出來

from langchain.agents import initialize_agent, Tool
from langchain.agents import AgentType
from langchain_community.chat_models.ollama import ChatOllama
import math


def calculate_sqrt(input_text: str) -> str:
    try:
        number = float(input_text.strip())
        result = math.sqrt(number)
        return f"The square root of {number} is {result}."
    except ValueError:
        return "Please provide a valid number."

def calculate_square(input_text: str) -> str:
    try:
        number = float(input_text.strip())
        result = number ** 2
        return f"The square of {number} is {result}."
    except ValueError:
        return "Please provide a valid number."

# 創建tool
sqrt_tool = Tool(
    name="SquareRootCalculator",
    func=calculate_sqrt,
    description="Calculate the square root of a number."
)

square_tool = Tool(
    name="SquareCalculator",
    func=calculate_square,
    description="Calculate the square of a number."
)

這邊要注意一下,模型在做決策的時候,是根據tool的**name**以及**description**這兩個屬性,所以這邊就要將名稱及功能寫清楚

接著就將agentExecutor寫出來並指定llm、工具、agentType等等

# LLM - ChatOllama
llm = ChatOllama(model="llama3")

# AgentExecutor
agent_executor = initialize_agent(
    tools=[sqrt_tool, square_tool],     # 指定工具
    llm=llm,
    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,  # AgentType
    verbose=True          
)

# AgentExecutor 運行
question = "What is the square root of 25?"
response = agent_executor.run(question)

print(response)

這樣agent就會調用適合的tool並回傳結果啦!

接下來我們會繼續實作其他AgentType!


LangChain Package


上一篇
<玩轉大語言模型> LangChain: Agent
系列文
LangChain、RAG、HuggingFace: 玩轉大語言模型12
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言